package com.haozhen.streamsink;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;

import javax.xml.bind.helpers.ValidationEventLocatorImpl;

/**
 * @author haozhen
 * @email haozh@ync1.com
 * @date 2021/2/26  0:16
 */
public class MySinkToRedis {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> data1 = env.socketTextStream("localhost",9999);


        FlinkJedisPoolConfig.Builder builder = new FlinkJedisPoolConfig.Builder();
        FlinkJedisPoolConfig localhost = builder.setHost("localhost").setPort(6379).build();


        RedisSink<Tuple2<String, String>> tuple2RedisSink = new RedisSink<>(localhost, new RedisMapper<Tuple2<String, String>>() {

            @Override
            public RedisCommandDescription getCommandDescription() {
                return new RedisCommandDescription(RedisCommand.LPUSH);
            }

            @Override
            public String getKeyFromData(Tuple2<String, String> value) {
                return value.f0;
            }

            @Override
            public String getValueFromData(Tuple2<String, String> value) {
                return value.f1;
            }
        });

        data1.map(new MapFunction<String, Tuple2<String,String>>() {
            @Override
            public Tuple2<String, String> map(String s) throws Exception {
                return new Tuple2<String,String>("haozhen",s);
            }
        }).addSink(tuple2RedisSink);

        env.execute();
    }
}

